package com.mySampleApplication.client.codeRule;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mySampleApplication.client.CodeRuleAtter.CodeRuleAtterService;
import com.mySampleApplication.client.CodeRuleAtter.CodeRuleAtterWindow;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;

import java.util.*;

public class dataObjecForm {
    private static ListGrid plistGrid;

    public static ListGrid getPlistGrid() {
        return plistGrid;
    }

    public static void setPlistGrid(ListGrid plistGrid) {
        dataObjecForm.plistGrid = plistGrid;
    }
    // 自定义的 Formatter
    private static class CustomCellFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
            return Integer.toString(rowNum + 1); // 返回当前行的序号（行号）
        }
    }
    public static Map<String,Object> getListGrid(ListGrid codeRuleListGrid, ListGridRecord frecord, Window winModal, TextItem modelItem,TextItem modelItemId) {
        Map<String,Object> map =new HashMap<>();
        // 创建一个列表网格控件
        ListGrid listGrid =getOp();

        ListGrid finalListGrid = listGrid;
        listGrid.setWidth100(); // 设置宽度为100%
        listGrid.setHeight100(); // 设置高度为100%
        // 设置列表网格显示网格线
        listGrid.setShowAllRecords(false); // 显示所有记录
        // 开启分页功能
        listGrid.setDataPageSize(10); // 每页显示的数据条数
        listGrid.setSelectionType(SelectionStyle.SINGLE);//开启单选框
        listGrid.setModalEditing(true);
        listGrid.setVirtualScrolling(false);
        listGrid.setShowRecordComponents(true);
        listGrid.setShowRecordComponentsByCell(true);

        ListGridField selectedCountriesField = new ListGridField("name", "Selected");
        selectedCountriesField.setWidth(70);
        listGrid.setFields(selectedCountriesField);
        listGrid.setSelectionType(SelectionStyle.SINGLE);
        listGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);

        // 定义列表网格的列
        ListGridField idField = new ListGridField("id", "序号");
        // 设置自定义的 Formatter
        idField.setCellFormatter(new CustomCellFormatter());
        idField.setWidth(50);
        ListGridField name_cn = new ListGridField("name_cn", "中文名称");
        ListGridField name_en = new ListGridField("name_en", "英文名称");
        listGrid.setFields(idField, name_cn,name_en);

        // 创建按钮和事件处理
        Button addButton = new Button("Add");
        addButton.setTitle("下一步");
        addButton.setShowRollOver(true);
        addButton.setShowDown(true);
        addButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                ListGridRecord selectedRecord = finalListGrid.getSelectedRecord();
                if(selectedRecord!=null){
                    Map<String, String> mapPage = new HashMap<>();
                    mapPage.put("pageSize", "1");
                    mapPage.put("pageNumber", "10");
                    Map<String, String> parameter = new HashMap<>();
                    parameter.put("db_model_id", selectedRecord.getAttribute("id"));

                    CodeRuleService.App.getInstance().getSelect(parameter, mapPage, new AsyncCallback<CodeRuleDto>() {
                        public void onSuccess(CodeRuleDto result) {
                            if( result.getKeyValueMap().size()<1){

                                editCodeRule(selectedRecord.getAttribute("id"),selectedRecord.getAttribute("name_cn"),codeRuleListGrid);
                                winModal.hide();
                            }else{
                                SC.warn("该数据对象已添加编码规则！进行修改即可！");
                            }
                        }
                        public void onFailure(Throwable caught) {
                            SC.warn("获取数据失败！");
                        }
                    });
                }else{
                    SC.warn("请选择数据对象！");
                }
            }
        });

        Button gbButton = new Button("gb");
        gbButton.setTitle("关闭");
        gbButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                winModal.hide();
            }
        });

        Button xzButton = new Button("xz");
        xzButton.setTitle("选择");
        xzButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                ListGridRecord selectedRecord = finalListGrid.getSelectedRecord();
//                frecord.setAttribute("sjdxid",selectedRecord.getAttribute("id"));
//                frecord.f
                modelItemId.setValue(selectedRecord.getAttribute("id"));
                modelItem.setValue(selectedRecord.getAttribute("name_cn"));
                winModal.hide();
            }
        });

        HLayout buttonLayout = new HLayout();
        buttonLayout.setMembersMargin(10);
        buttonLayout.setAlign(Alignment.RIGHT);

        if(frecord!=null){
            buttonLayout.addMembers(xzButton,gbButton);
        }else{
            buttonLayout.addMembers(addButton,gbButton);
        }


        // 添加 CellClickHandler 处理单击事件
        listGrid.addCellClickHandler(new CellClickHandler() {
            @Override
            public void onCellClick(CellClickEvent event) {
                // 获取单击发生的行和列
                int rowNum = event.getRowNum();
                int colNum = event.getColNum();

                // 判断是否单击了指定的列
                if (colNum == listGrid.getFieldNum("fdmc")) {
                    // 获取单击处的数据
                    ListGridRecord record = listGrid.getRecord(rowNum);
//                    String value = record.getAttribute("fdmc");
//                    SC.say( "弹窗显示详情！"+record.getAttribute("fdmc"));
                    detRecord(record,listGrid,frecord);
                    // 执行其他操作...
                }
            }
        });

        setPlistGrid(listGrid);
        map.put("listGrid",listGrid);
        map.put("buttonLayout",buttonLayout);
        return map;
    }

    private static ListGrid getOp(){
        return new ListGrid() {
            @Override
            protected Canvas createRecordComponent(final ListGridRecord record, Integer colNum) {
                String fieldName = this.getFieldName(colNum);
                if (fieldName.equals("actionField")) {
                    HLayout recordCanvas = new HLayout(3);
                    recordCanvas.setHeight(22);
                    recordCanvas.setWidth100();
                    recordCanvas.setAlign(Alignment.CENTER);
                    IButton chartImg = new IButton();
                    chartImg.setTitle("删除");
                    chartImg.setIcon("[SKIN]/actions/remove.png"); // 设置图标路径
                    chartImg.setWidth(60);
                    chartImg.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            SC.ask("是否删除该条数据?", new BooleanCallback() {
                                public void execute(Boolean value) {
                                    if (value != null && value) {
                                        deleteRecord(record,event);
                                    } else {

                                    }
                                }
                            });
                        }
                    });
                    recordCanvas.addMember(chartImg);

                    return recordCanvas;
                } else {
                    return null;
                }
            }
        };
    }

    private static void detRecord(final ListGridRecord record,ListGrid listGrid,ListGridRecord frecord) {
        Window dialog=CodeRuleAtterWindow.getShowWindow(true,900,350,"分段详情",record,listGrid,frecord);
        dialog.show();
        // 执行编辑操作
    }

    private static void editCodeRule(String id,String name,ListGrid listGrid) {
        Window bmgf = CodingSpecificationwindow.getShowWindow(800,390,"(2/5)编辑编码规范",null,listGrid,id,name);
        bmgf.draw();
    }

    // 删除记录函数
    private static void deleteRecord(ListGridRecord record, ClickEvent event) {
        ListGrid listGrid = getPlistGrid();
        int[] ids = new int[0];
        ids[0]=Integer.parseInt(record.getAttribute("id"));
        CodeRuleAtterService.App.getInstance().setDelete(ids, new AsyncCallback<String>() {
            public void onSuccess(String result) {
                listGrid.removeData(record);
                // 执行删除操作
                SC.say( "删除数据成功！");
                //list.addAll(result);
            }
            public void onFailure(Throwable caught) {
                SC.warn("删除数据失败！");
            }
        });

    }


}
